package org.study.flex.api.custom;

import com.alibaba.druid.pool.DruidDataSource;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年11月19日
 */
public class FlexDataSourceFactory implements DataSourceFactory {
    private Properties props;

    @Override
    public void setProperties(Properties props) {
        this.props = props;
    }

    @Override
    public DataSource getDataSource() {
        // 获取数据源基本属性
        String dataSourceKey = props.getProperty("dataSourceKey", "flex_ds_default");
        String driver = props.getProperty("driver");
        String url = props.getProperty("url");
        String username = props.getProperty("username");
        String password = props.getProperty("password");

        // 使用MyBatis自带的org.apache.ibatis.datasource.unpooled.UnpooledDataSource
        PooledDataSource pooledDataSource = new PooledDataSource(driver, url, username, password);
        // 使用MyBatis自带的org.apache.ibatis.datasource.pooled.PooledDataSource
        UnpooledDataSource unpooledDataSource = new UnpooledDataSource(driver, url, username, password);
        // 使用 Druid
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        // 使用Hikari
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(driver);
        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);
        // 返回 FlexDataSource 数据源
        return new FlexDataSource(dataSourceKey, pooledDataSource);
    }
}
